function encodeBase64(str) {
  try {
    return btoa(unescape(encodeURIComponent(str)));
  } catch (_e) {
    return str;
  }
}
function decodeBase64(str) {
  try {
    return decodeURIComponent(escape(atob(str)));
  } catch (_e) {
    return str;
  }
}

export async function migrateStorage() {
  // Reserved for future schema migrations
}

export async function getFromStorage(key) {
  return new Promise((resolve) => {
    chrome.storage.local.get([key], (res) => resolve(res[key]));
  });
}

export async function saveToStorage(key, value) {
  return new Promise((resolve) => {
    chrome.storage.local.set({ [key]: value }, resolve);
  });
}

export async function exportAllData() {
  return new Promise((resolve) => {
    chrome.storage.local.get(null, (res) => resolve(res));
  });
}

export async function importAllData(obj) {
  return new Promise((resolve) => {
    chrome.storage.local.set(obj, resolve);
  });
}

export function maybeEncrypt(value, enable) {
  if (!enable) return value;
  try {
    return { __enc: true, v: encodeBase64(JSON.stringify(value)) };
  } catch (_e) {
    return value;
  }
}

export function maybeDecrypt(value) {
  if (!value || value.__enc !== true) return value;
  try {
    return JSON.parse(decodeBase64(value.v));
  } catch (_e) {
    return value;
  }
}
